package org.mytang.fairydust.core.demo;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

/**
 * @author zhaomu
 */
public class JvmDemo {

    private static Connection conn;

    public static Connection getConn(String url, String user, String pass) throws Exception {
        if (conn == null) {
            //创建URL数组
            URL[] urls = {new URL("file:mysql-connector-java-5.1.12-bin.jar")};
            //以默认的ClassLoader作为父类的ClassLoader, 创建URLClassLoader
            URLClassLoader myClassLoader = new URLClassLoader(urls);
            System.out.println("默认父类加载器： " + myClassLoader.getParent());
            System.out.println("默认父类加载器路径： " + myClassLoader.getParent().getResource(""));
            System.out.println("当前的类加载器路径： " + myClassLoader.getResource(""));

            //加载 mysql-connector-java-5.1.12-bin.jar包里面的\com\mysql\jdbc\Driver.class 驱动，并创建实例
            //加载路径 myClassLoader.getResource("")
            Driver driver =  (Driver)myClassLoader.loadClass("com.mysql.jdbc.Driver").newInstance();
            //创建一个设置jdbc连接属性的Properties对象
            Properties props = new Properties();
            props.setProperty("user", user);
            props.setProperty("password", pass);
            //调用driver的connection来取得连接
            conn = driver.connect(url, props);
        }
        return conn;
    }



    public static void main(String[] args) throws Exception {
        System.out.println("user.dir: " + System.getProperty("user.dir"));
        System.out.println(getConn("jdbc:mysql://localhost:3306/mysql", "root", ""));
    }
}
